package mysql

import (
	"Godzilla/conf/databases"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

type DB struct {
	db *sql.DB
}

// NewMysqlConn 创建mysql 连接
func NewMysqlConn() (*DB, error) {

	var (
		Name 		string
		Host 		string
		Port 		string
		User 		string
		Password 	string
	)

	Name 		= databases.GetMysqlConfig("Name")
	Host 		= databases.GetMysqlConfig("Host")
	Port 		= databases.GetMysqlConfig("Port")
	User 		= databases.GetMysqlConfig("User")
	Password 	= databases.GetMysqlConfig("Password")
	db, errMysql := sql.Open("mysql", User + ":" + Password + "@tcp(" + Host + ":" + Port + ")/" + Name + "?charset=utf8mb4")
	return &DB{
		db: db,
	}, errMysql
}

func (d DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
	log.Println(query, args)
	return d.db.Query(query, args...)
}

func (d DB) Prepare(query string, args ...interface{}) (*sql.Stmt, error) {
	log.Println(query, args)
	return d.db.Prepare(query)
}

func (d DB) PrepareAndExec(query string, args ...interface{}) (sql.Result, error) {
	log.Println(query, args)
	stmt, err := d.db.Prepare(query)
	if err != nil {
		return nil, err
	}
	result, errStmt := stmt.Exec(args ...)
	if errStmt != nil {
		return nil, errStmt
	}
	return result,nil
}

func (d DB) Exec(query string, args ...interface{}) (sql.Result, error){
	log.Println(query, args)
	return d.db.Exec(query, args ...)
}


// GetResultRow 获取返回值，获取一条
func GetResultRow(rows *sql.Rows) map[string]string{
	columns, _ := rows.Columns()
	scanArgs := make([]interface{}, len(columns))
	values := make([]interface{}, len(columns))
	for j := range values {
		scanArgs[j] = &values[j]
	}
	record := make(map[string]string)
	for rows.Next() {
		//将行数据保存到record字典
		rows.Scan(scanArgs...)
		for i, v := range values {
			if v != nil {
				//fmt.Println(reflect.TypeOf(col))
				//record[columns[i]] = string(v.([]byte))
				//record[columns[i]] = fmt.Sprintf("%s", v)
				//用断言转数据类型
				switch v := v.(type) {
				case int64:
					record[columns[i]] = fmt.Sprintf("%d", v)
				case int:
					record[columns[i]] = fmt.Sprintf("%d", v)
				case int32:
					record[columns[i]] = fmt.Sprintf("%d", v)
				default:
					record[columns[i]] = fmt.Sprintf("%s", v)
				}
			}
		}
	}
	return record
}

// GetResultRows 获取所有
func GetResultRows(rows *sql.Rows) map[int]map[string]string {
	//返回所有列
	columns, _ := rows.Columns()
	//这里表示一行所有列的值，用[]byte表示
	vals := make([][]byte, len(columns))
	//这里表示一行填充数据
	scans := make([]interface{}, len(columns))
	//这里scans引用vals，把数据填充到[]byte里
	for k, _ := range vals {
		scans[k] = &vals[k]
	}
	i := 0
	result := make(map[int]map[string]string)
	for rows.Next() {
		//填充数据
		rows.Scan(scans...)
		//每行数据
		row := make(map[string]string)
		//把vals中的数据复制到row中
		for k, v := range vals {
			key := columns[k]
			//这里把[]byte数据转成string
			row[key] = string(v)
		}
		//放入结果集
		result[i] = row
		i++
	}
	return result
}